package com.probiz.estore.product.service.impl;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.attribute.ProductAttrValue;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.inventory.Inventory;
import com.probiz.estore.common.model.product.PriceInterval;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductAttGroup;
import com.probiz.estore.common.model.product.ProductAttGroupItem;
import com.probiz.estore.common.model.product.ProductDescription;
import com.probiz.estore.common.model.product.ProductFilter;
import com.probiz.estore.common.model.product.ProductMedia;
import com.probiz.estore.common.model.product.ProductSku;
import com.probiz.estore.common.model.product.ProductSkuOptionValue;
import com.probiz.estore.common.model.product.ProductStat;
import com.probiz.estore.common.model.product.ProductType;
import com.probiz.estore.common.model.product.ProductTypeBrand;
import com.probiz.estore.common.model.product.ProductTypeSkuOption;
import com.probiz.estore.common.model.product.SkuOption;
import com.probiz.estore.common.model.product.SkuOptionValue;
import com.probiz.estore.common.service.OrderService;
import com.probiz.estore.core.util.ArrayUtil;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.core.util.StringUtil;
import com.probiz.estore.customer.service.FavoriteManager;
import com.probiz.estore.inventory.service.InventoryManager;
import com.probiz.estore.product.ProductConstants;
import com.probiz.estore.product.model.ProductFilterGroup;
import com.probiz.estore.product.model.ProductFullyModel;
import com.probiz.estore.product.model.ProductSearchCriteria;
import com.probiz.estore.product.model.ProductUniBulkEditModel;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.product.service.ProductAttGroupItemManager;
import com.probiz.estore.product.service.ProductAttGroupManager;
import com.probiz.estore.product.service.ProductAttrValueManager;
import com.probiz.estore.product.service.ProductDescriptionManager;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductMediaManager;
import com.probiz.estore.product.service.ProductPackageItemManager;
import com.probiz.estore.product.service.ProductSkuManager;
import com.probiz.estore.product.service.ProductSkuOptionValueManager;
import com.probiz.estore.product.service.ProductStatManager;
import com.probiz.estore.product.service.ProductTypeManager;
import com.probiz.estore.product.service.SkuOptionManager;
import com.probiz.estore.product.service.WholesalePriceManager;
import com.probiz.estore.product.util.ProdCodeGenerator;
import com.probiz.estore.sales.service.RecommendedProductManager;
import com.probiz.estore.solrsearch.service.SolrSearchService;

public class ProdMainManagerImpl implements ProdMainManager {
	protected final transient Log	logger	= LogFactory.getLog(getClass());
	private static String VIEW_PRODUCT_ID_LIST = "VIEW_PRODUCT_ID_LIST";
	
	private static int URI_PRICE_LOCATOR = 0;	//价格的位置标记定0
	private static int URI_BRAND_LOCATOR = 1;	//品牌的位置标记定1
	private static int URI_ATTR_LOCATOR  = 2;	//属性的位置标记从2开始
	
	private ProductManager productManager;
	private ProductDescriptionManager productDescriptionManager;
	private ProductMediaManager productMediaManager;
	private ProductSkuManager productSkuManager;
	private WholesalePriceManager wholesalePriceManager;
	private ProductStatManager productStatManager;
	private ProductCategoryManager productCategoryManager;
	private ProductAttrValueManager productAttrValueManager;
	private ProductAttGroupManager productAttGroupManager;
	private ProductAttGroupItemManager productAttGroupItemManager;
	private ProductTypeManager productTypeManager;
	private ProductSkuOptionValueManager productSkuOptionValueManager;
	private InventoryManager inventoryManager;
	private RecommendedProductManager recommendedProductManager;
	private SkuOptionManager skuOptionManager;
	private ProductPackageItemManager productPackageItemManager;
	private FavoriteManager favoriteManager;
	
	
	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}

	public void setProductDescriptionManager(
			ProductDescriptionManager productDescriptionManager) {
		this.productDescriptionManager = productDescriptionManager;
	}

	public void setProductSkuManager(ProductSkuManager productSkuManager) {
		this.productSkuManager = productSkuManager;
	}

	public void setWholesalePriceManager(
			WholesalePriceManager wholesalePriceManager) {
		this.wholesalePriceManager = wholesalePriceManager;
	}

	public void setProductMediaManager(ProductMediaManager productMediaManager) {
		this.productMediaManager = productMediaManager;
	}

	public void setProductStatManager(ProductStatManager productStatManager) {
		this.productStatManager = productStatManager;
	}

	public void setProductCategoryManager(
			ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}

	
	public void setProductAttrValueManager(
			ProductAttrValueManager productAttrValueManager) {
		this.productAttrValueManager = productAttrValueManager;
	}

	public void setProductAttGroupManager(
			ProductAttGroupManager productAttGroupManager) {
		this.productAttGroupManager = productAttGroupManager;
	}

	public void setProductAttGroupItemManager(
			ProductAttGroupItemManager productAttGroupItemManager) {
		this.productAttGroupItemManager = productAttGroupItemManager;
	}

	

	public void setProductTypeManager(ProductTypeManager productTypeManager) {
		this.productTypeManager = productTypeManager;
	}

	public void setProductSkuOptionValueManager(
			ProductSkuOptionValueManager productSkuOptionValueManager) {
		this.productSkuOptionValueManager = productSkuOptionValueManager;
	}

	
	public void setInventoryManager(InventoryManager inventoryManager) {
		this.inventoryManager = inventoryManager;
	}

	
	public void setRecommendedProductManager(RecommendedProductManager recommendedProductManager) {
		this.recommendedProductManager = recommendedProductManager;
	}

	public void setSkuOptionManager(SkuOptionManager skuOptionManager) {
		this.skuOptionManager = skuOptionManager;
	}

	public void setProductPackageItemManager(
			ProductPackageItemManager productPackageItemManager) {
		this.productPackageItemManager = productPackageItemManager;
	}
	

	public void setFavoriteManager(FavoriteManager favoriteManager) {
		this.favoriteManager = favoriteManager;
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#saveFully(com.probiz.estore.product.model.ProductFullyModel)
	 */
	public Map<String, Object> saveFully(ProductFullyModel model) throws Exception{
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		Product product = model.getProduct();
		 
		//start:生成规格信息和检查是否有重复
		String[] skuOptionValueInfos = productSkuManager.getSkuOptionValueInfos(returnMsgs,model.getSkuIds(), model.getSkuOptionIds(), model.getSkuOptionValueIdsList()) ;
		if(returnMsgs.containsKey("error")){
			return returnMsgs;
		}
		//end:生成规格信息和检查是否有重复
		
		//start:设置商品编码并检查
		if(StringUtils.isBlank(product.getProductCode())){
			boolean isCodeAvailable = false;
			do{
				String productCode = ProdCodeGenerator.generateProductCode();
				Long size = productManager.getSizeByProductCodeByNotProductId(productCode, product.getProductId());
				if(size==0){
					//该商品编码可用
					isCodeAvailable = true;
					product.setProductCode(productCode);
				}
			}while(!isCodeAvailable);
		}else{
			//用getSizeByProductCodeByNotProductId而不用getProductByProductCode的原因在于调用后者的时候会有update操作，造成数据库有两个相同code的商品，出错
			Long size = productManager.getSizeByProductCodeByNotProductId(product.getProductCode(), product.getProductId());
			
			if(size>=1){
				//商品编码重复
				returnMsgs.put("error", I18nUtil.getInstance().getMessage("product.productCode.repeated"));
				productManager.evict(product); //必须把product evict出session 否则会有update操作
				return returnMsgs;
			}
		}
		//end:设置商品编码并检查

		// start:保存描述信息
		ProductDescription productDescription = product.getProductDescription();
		if (productDescription == null) {
			productDescription = new ProductDescription();
		}

		productDescription.setShortDescription(model.getShortDescription());
		productDescription.setFullDescription(model.getDescription());
		productDescriptionManager.save(productDescription);
		product.setProductDescription(productDescription);
		// end: 保存描述信息

		// start:保存统计信息
		ProductStat productStat = product.getProductStat();
		if (productStat == null) {
			productStat = new ProductStat();
			productStat.setViewCount(0);
			productStat.setBuyCount(0);
			productStat.setBuyTimes(0);
			productStat.setNumOfPositiveRate(0);
			productStat.setNumOfNeutralRate(0);
			productStat.setNumOfNegativeRate(0);
			productStat.setReviewCount(0);
			productStat.setOnShowReviewCount(0);
			productStat.setReviewScore(new BigDecimal("0"));
			
		}
		productStatManager.save(productStat);
		product.setProductStat(productStat);
		// end: 保存统计信息
		
		// start:保存主体
		if (null == product.getId()) {
			product.setShelveTime(new Date());
			// start:更新产品目录信息
			updateProductCategoryItemCount(product.getCategoryId(), 1, 1);
			// end:更新产品目录信息
		} else {
		}
		if(product.getProductKind() == null){ 
			//默认是商品
			product.setProductKind(Product.PRODUCTKIND_PRODUCT);
		}	
		productManager.save(product);
		// end:保存主体


		// start:保存SKU信息
		List<String> newSkuIds = productSkuManager
				.saveSkusFromArrays(product, returnMsgs,model.getSkuIds(), model
						.getSkuCodes(), model.getSkuImageUrls(),model.getListPrices(),model.getPrices(),model.getSalePrices(),model.getWeights(),skuOptionValueInfos);
		if(returnMsgs.containsKey("error")){
			throw new Exception((String)returnMsgs.get("error"));
		}
		if(0 == newSkuIds.size()){
			//防止出现没有货品的错误情况
			throw new Exception("Not Defined any SKU.货品为空异常");
		}
		returnMsgs.put("newSkuIds", newSkuIds);
		returnMsgs.put("skuCodes", model.getSkuCodes());//修改后的skuCode
		
		product.setDefaultProductSkuId(Integer.parseInt(newSkuIds.get(0))); //设置默认sku
		ProductSku defaultSku = productSkuManager.getById(product.getDefaultProductSkuId());
		if(null != defaultSku.getSalePrice()){
			product.setPrice(defaultSku.getSalePrice());
		}else{
			product.setPrice(defaultSku.getPrice());
		}
		
		
		
		// end:保存SKU信息
		
		

		// -----import
		String[] wpSkuIds = getNewWpSkuIds(model.getOldSkuIds(), newSkuIds,
				model.getOldWpSkuIds());

		// start:保存wholesalePrice信息
		List<String> newWpIds = wholesalePriceManager
				.saveWholesalePriceFromArrays(newSkuIds.toArray(new String[0]),wpSkuIds, model.getWpIds(), model
						.getWpMinQuantitys(), model.getWpMaxQuantitys(), model
						.getWpPrices(), model.getWpDeliveryDays());
		returnMsgs.put("newWpIds", newWpIds);
		returnMsgs.put("newWpSkuIds", wpSkuIds);
		// end:保存wholesalePrice信息
		
		//start:保存规格信息
		for(int i=0; i< newSkuIds.size(); i++){
			List<String> relationOptionValueIds = new ArrayList<String>(); //存放sku对应的规格值id
			for(String[] skuOptionValueIds: model.getSkuOptionValueIdsList()){
				relationOptionValueIds.add(skuOptionValueIds[i]);
			}
			productSkuOptionValueManager.saveProductSkuOptionValueFromArrays(newSkuIds.get(i), relationOptionValueIds.toArray(new String[0]));
		}
		
		//end:保存规格信息

		// start:保存库存信息
		inventoryManager.saveInventorysFromArrays(newSkuIds.toArray(new String[0]), model.getInventorys());
		// end:保存库存信息
		
		// start:保存媒体信息
		List<String> newMediaIds = productMediaManager.saveMediasFromArrays(
				product, model.getMediaIds(), model.getMediaUrls(), model
						.getMediaTypes(), model.getMediaDescs());
		returnMsgs.put("newMediaIds", newMediaIds);
		//保存主图
		if(!ArrayUtils.isEmpty(model.getMediaUrls())){
			for(int i=0; i< model.getMediaTypes().length;i++){
				if(model.getMediaTypes()[i].equals(ProductMedia.TYPE_IMAGE.toString())){
					product.setImageUrl(model.getMediaUrls()[i]);
					if(product.getIsSetMultiSkus().equals(Constants.FLAG_FALSE)){
						defaultSku.setImageUrl(model.getMediaUrls()[i]);
						productSkuManager.save(defaultSku);
					}
					break;
				}
			}
		}else{
			//清空冗余
			product.setImageUrl("");
			if(product.getIsSetMultiSkus().equals(Constants.FLAG_FALSE)){
				defaultSku.setImageUrl("");
				productSkuManager.save(defaultSku);
			}
		}
		// end:保存媒体信息
		
		// start:保存产品特性
		productAttrValueManager.saveProductAttrValueFromRequest(product, model
				.getAttributeValues());
		// end:保存产品特性
		
		// start:关联商品
		recommendedProductManager.saveRecommendedProductsFromArrays(product, null, model.getRecommendedTypeIds(), model.getRecommendedProductIds());
		// end:关联商品
		
		//start:商品包
		productPackageItemManager.saveProductPackageItemFromArrays(product.getDefaultProductSkuId(), model.getItemSkuIds(), model.getItemQuantitys());
		//end:商品包
		
		productManager.save(product);

		// start:flush-必须先对要保存的对象进行flush操作，否则会报“possible nonthreadsafe access to
		// session”错误，原因是：将对象过早的与Session拆离，造成了Session的insertions和entityEntries中内容的不同步
//		wholesalePriceManager.flush();
//		productSkuManager.flush();
		productManager.flush();
		// end:flush

		
		
		return returnMsgs;

	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#saveFullyForImport(com.probiz.estore.common.model.product.Product)
	 */
	public Product saveFullyForImport(Product product){
		if(!product.isSkuImportFlag()){
			//==============导入的是商品和货品=============================
			// start:保存描述信息
			ProductDescription productDescription = product.getProductDescription();
			if (productDescription == null) {
				productDescription = new ProductDescription();
			}
			productDescriptionManager.save(productDescription);
			product.setProductDescription(productDescription);
			// end: 保存描述信息
	
			// start:保存统计信息
			ProductStat productStat = product.getProductStat();
			if (productStat == null) {
				productStat = new ProductStat();
				productStat.setViewCount(0);
				productStat.setBuyCount(0);
				productStat.setBuyTimes(0);
				productStat.setNumOfPositiveRate(0);
				productStat.setNumOfNeutralRate(0);
				productStat.setNumOfNegativeRate(0);
				productStat.setReviewCount(0);
				productStat.setOnShowReviewCount(0);
				productStat.setReviewScore(new BigDecimal("0"));
				
			}
			productStatManager.save(productStat);
			product.setProductStat(productStat);
			// end: 保存统计信息
			
			// start:保存主体
			if (null == product.getId()) {
				product.setShelveTime(new Date());
				// start:更新产品目录信息
				updateProductCategoryItemCount(product.getCategoryId(), 1, 1);
				// end:更新产品目录信息
			} else {
			}
			if(product.getProductKind() == null){ 
				//默认是商品
				product.setProductKind(Product.PRODUCTKIND_PRODUCT);
			}	
			product.setSortOrder(Product.DEFAULT_SORTORDER);
			if(product.getStatus().equals(Product.STATUS_ACTIVE)){
				product.setShelveTime(new Date());
			}else if(product.getStatus().equals(Product.STATUS_NOTACTIVE)){
				product.setOffshelveTime(new Date());
			}
			if(product.getImportProductSku().getImportSkuOptionValueList().size()>0){
				product.setIsSetMultiSkus(Constants.FLAG_TRUE);
			}else{
				product.setIsSetMultiSkus(Constants.FLAG_FALSE);
			}
			productManager.saveImport(product);
			// end:保存主体
			
			// start:保存产品特性
			productAttrValueManager.saveProductAttrValueFromRequest(product, product.getImportAttributeValueList());
			// end:保存产品特性
		}else{
			productManager.saveImport(product);
		}
		
		// start:保存SKU信息
		ProductSku productSku = product.getImportProductSku();
		productSku.setProduct(product);
		productSku.setStatus(Constants.FLAG_TRUE);
		productSku.setSkuOptionValueInfo(productSku.getImportSkuOptionValueInfo());
		productSku.setSortOrder(product.getProductSkus().size());
		productSkuManager.save(productSku);
		if(!product.isSkuImportFlag()){
			//默认
			product.setDefaultProductSkuId(productSku.getProductSkuId()); //设置默认sku
			if(null != productSku.getSalePrice()){
				product.setPrice(productSku.getSalePrice());
			}else{
				product.setPrice(productSku.getPrice());
			}
			productManager.saveImport(product);
		}
		// end:保存SKU信息
		
		
		// start:保存wholesalePrice信息
		wholesalePriceManager.saveWholesalePriceForImport(productSku, productSku.getImportWholesalePrices());
		// end:保存wholesalePrice信息
		
		// start:保存库存信息
		Inventory inventory = productSku.getInventory();
		if(null == inventory.getIntegerId()){
			inventory.setAllocatedQuantity(0);
			inventory.setReorderMinimnm(0);
		}
		inventoryManager.save(inventory);
		productSkuManager.save(productSku);
		// end:保存库存信息
		
		// start:保存规格信息 最后保存
		List<String> relationOptionValueIds = new ArrayList<String>(); //存放sku对应的规格值id
		for(SkuOptionValue skuOptionValue: productSku.getImportSkuOptionValueList()){
			relationOptionValueIds.add(skuOptionValue.getSkuOptionValueId().toString());
		}
		productSkuOptionValueManager.saveProductSkuOptionValueFromArrays(productSku.getProductSkuId().toString(), relationOptionValueIds.toArray(new String[0]));
		// end:  保存规格信息
		
		
		return product;
	}
	

	/**
	 * 更新产品目录的产品数量,包括其上面的祖辈目录
	 * 
	 * @param categoryId
	 *            产品目录id
	 * @param itemCount
	 *            要改变的数量，可正可负
	 * @param activeItemCount
	 *            要改变的激活数量，可正可负
	 */
	private void updateProductCategoryItemCount(Integer categoryId,
			Integer itemCount, Integer activeItemCount) {
		ProductCategory productCategory = productCategoryManager
				.getById(categoryId);
		do {

			productCategory.setItemCount(productCategory.getItemCount()
					.intValue()
					+ itemCount.intValue());
			productCategory.setActiveItemCount(productCategory
					.getActiveItemCount().intValue()
					+ activeItemCount.intValue());
			productCategoryManager.save(productCategory);
			productCategory = productCategory.getParent();

		} while (null != productCategory);

	}
	

	


	/**
	 * 根据oldSkuIds 、 newSkuIds以及oldWpSkuIds 生成newWpSkuIds
	 * @param oldSkuIds
	 * @param newSkuIds
	 * @param oldWpSkuIds
	 * @return
	 */
	private String[] getNewWpSkuIds(String[] oldSkuIds, List<String> newSkuIds,
			String[] oldWpSkuIds) {
		String[] newWpSkuIds = (String[]) ArrayUtils.clone(oldWpSkuIds);
		for (int i = 0; i < oldWpSkuIds.length; i++) {
			String oldSkuId = oldWpSkuIds[i].substring(2);
			int index = ArrayUtils.indexOf(oldSkuIds, oldSkuId);
			String newSkuId = newSkuIds.get(index);
			newWpSkuIds[i] = newSkuId;
		}

		return newWpSkuIds;
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#deleteFully(com.probiz.estore.product.model.Product)
	 */
	public short deleteFully(Product product) {
		OrderService orderService = (OrderService)ContextUtil.getSpringBeanById("orderService");
		short orderHistoryStatus = orderService.getProductCircsInSalesOrder(product.getProductId());
		if(orderHistoryStatus == (short)2){
			//case:不存在任何订单，物理删除
			if (null != product.getProductDescriptionId())productDescriptionManager.deleteById(product.getProductDescriptionId());
			if (null != product.getProductStatId())	productStatManager.deleteById(product.getProductStatId());
			//删除库存
			for(ProductSku sku : product.getProductSkus()){
				if(null != sku.getInventory())inventoryManager.deleteById(sku.getInventoryId());
			}
			//删除收藏夹
			favoriteManager.deleteFavoriteProducts(product.getProductId());
			
			productManager.deleteById(product.getProductId());
			if(product.getStatus().shortValue() == Product.STATUS_ACTIVE.shortValue()){
				updateProductCategoryItemCount(product.getCategoryId(), -1, -1);
			}else{
				updateProductCategoryItemCount(product.getCategoryId(), -1, 0);
			}
			if(ConfigUtil.getInstance().isOpenFulltextSearch()){
	        	//删除solr索引
	        	SolrSearchService  solrSearchService = (SolrSearchService)ContextUtil.getInstance().getSpringBeanById("solrSearchService");
	        	solrSearchService.deleteIndex(product.getProductId()+"p");
	        }
			return DELETE_STATUS_PHYSICAL;
		}else if(orderHistoryStatus == (short)1){
			//case:存在处理中的订单，不允许删除
			return DELETE_STATUS_FALSE;
		}else if(orderHistoryStatus == (short)0){
			//case:仅存在在已经归档的订单，逻辑删除，变成归档状态
			if(product.getStatus().shortValue() == Product.STATUS_ACTIVE.shortValue()){
				product.setStatus(Product.STATUS_LOGICAL_DELETED);
				productManager.save(product);
				updateProductCategoryItemCount(product.getCategoryId(), -1, -1);
			}else if(product.getStatus().shortValue() == Product.STATUS_LOGICAL_DELETED.shortValue()){
				//本身已经是已归档 do nothing
			}else{
				product.setStatus(Product.STATUS_LOGICAL_DELETED);
				productManager.save(product);
				updateProductCategoryItemCount(product.getCategoryId(), -1, 0);
			}
			
			return DELETE_STATUS_LOGICAL;
		}
		return DELETE_STATUS_FALSE;

	}


	/*
	 * 产品上架 方法名称必须加入do前缀，否则会报错误：Illegal attempt to associate a collection
	// with two open sessions
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#doShelve(com.probiz.estore.common.model.product.Product)
	 */
	public void doShelve(Product product) {
		product.setStatus(Product.STATUS_ACTIVE);
		product.setShelveTime(new Date());
		productManager.save(product);
		updateProductCategoryItemCount(product.getCategoryId(), 0, 1);
	}

	public void doShelve(Integer productId) {
		Product product = productManager.getById(productId);
		doShelve(product);
	}

	public void doShelve(Integer[] productIdList) {
		for (Integer productId : productIdList) {
			doShelve(productId);
		}
	}

	public void doOffShelve(Product product) {
		// 注意：产品下架时候不需要更改上架和过期时间，因为这些属性已经没有意义。
		product.setStatus(Product.STATUS_NOTACTIVE);
		product.setOffshelveTime(new Date());
		productManager.save(product);
		updateProductCategoryItemCount(product.getCategoryId(), 0, -1);
	}

	public void doOffShelve(Integer productId) {
		Product product = productManager.getById(productId);
		doOffShelve(product);
	}

	public void doOffShelve(Integer[] productIdList) {
		for (Integer productId : productIdList) {
			doOffShelve(productId);
		}
	}

	/**
	 * 批修改商品名称
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditProductName(Product  product, ProductUniBulkEditModel model) {
		if(model.getNameCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getNameMethod()){
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getNamePrefix()) && (model.getNamePrefix() + product.getProductName()).length() <= 100) {
					product.setProductName(model.getNamePrefix() + product.getProductName());
				}
				if (StringUtils.isNotBlank(model.getNameSuffix()) && (model.getNameSuffix() + product.getProductName()).length() <= 100) {
					product.setProductName( product.getProductName() + model.getNameSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getNameFindAndReplaceOldString())) {
					String newString = product.getProductName().replace(model.getNameFindAndReplaceOldString(),	model.getNameFindAndReplaceNewString());
					if (newString.length() <= 100)
						product.setProductName(newString);
				}
				break;
			default: break;	
		}
		
		
	}
	
	/**
	 * 修改目录
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditCategory(Product product,	ProductUniBulkEditModel model) {
		if(model.getCategoryCheck().shortValue() != Constants.FLAG_TRUE)return;
		if(model.getCategoryId() != null){
			product.setCategoryId(model.getCategoryId());
		}
		
	}
	
	/**
	 * 修改商品状态
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditStatus(Product product,	ProductUniBulkEditModel model) {
		if(model.getStatusCheck().shortValue() != Constants.FLAG_TRUE)return;
		if(model.getStatus() != null){
			product.setStatus(model.getStatus());
		}
		
	}
	
	/**
	 * 修改销售计量单位
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditSalesMeasureUnitName(Product product,	ProductUniBulkEditModel model) {
		if(model.getSalesMeasureUnitNameCheck().shortValue() != Constants.FLAG_TRUE)return;
		product.setSalesMeasureUnitName(model.getSalesMeasureUnitName());
	}
	
	/**
	 * 修改最少订购量
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditMinOrderQuantity(Product product,	ProductUniBulkEditModel model) {
		if(model.getMinOrderQuantityCheck().shortValue() != Constants.FLAG_TRUE)return;
		if(model.getMinOrderQuantity() != null){
			product.setMinOrderQuantity(model.getMinOrderQuantity());
		}else{
			product.setMinOrderQuantity(null);
		}
	}
	
	
	
	/**
	 * 修改品牌
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditBrand(Product product,ProductUniBulkEditModel model) {
		if(model.getBrandCheck().shortValue() != Constants.FLAG_TRUE)return;
		if(model.getBrandId() != null){
			//必须是这个商品的商品类型所关联的品牌才生效
			boolean flag = false;
			for(ProductTypeBrand productTypeBrand : product.getProductType().getProductTypeBrands()){
				if(productTypeBrand.getBrand().getBrandId().equals(model.getBrandId())){
					flag = true;
					break;
				}
			}
			if(flag){
				product.setBrandId(model.getBrandId());
			}	
		}else{
			product.setBrand(null);
		}
		
	}
	
	/**
	 * 修改关键词
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditKeywords(Product product,ProductUniBulkEditModel model) {
		if(model.getKeywordsCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getKeywordsMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				product.setKeywords(model.getKeywords());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getKeywordsPrefix()) && (model.getKeywordsPrefix() + product.getKeywords()).length() <= 250) {
					product.setKeywords(model.getKeywordsPrefix() + product.getKeywords());
				}
				if (StringUtils.isNotBlank(model.getKeywordsSuffix()) && (model.getKeywordsSuffix() + product.getKeywords()).length() <= 250) {
					product.setKeywords( product.getKeywords() + model.getKeywordsSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getKeywordsFindAndReplaceOldString())) {
					String newString = product.getKeywords().replace(model.getKeywordsFindAndReplaceOldString(),	model.getKeywordsFindAndReplaceNewString());
					if (newString.length() <= 250)
						product.setKeywords(newString);
				}
				break;
			default: break;	
		}
	}
	
	/**
	 * 修改简单介绍
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditShortDescription(Product product,	ProductUniBulkEditModel model) {
		if(model.getShortDescriptionCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		ProductDescription productDescription = product.getProductDescription();
		switch(model.getShortDescriptionMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				productDescription.setShortDescription(model.getShortDescription());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getShortDescriptionPrefix()) && (model.getShortDescriptionPrefix() + productDescription.getShortDescription()).length() <= 500) {
					productDescription.setShortDescription(model.getShortDescriptionPrefix() + productDescription.getShortDescription());
				}
				if (StringUtils.isNotBlank(model.getShortDescriptionSuffix()) && (model.getShortDescriptionSuffix() + productDescription.getShortDescription()).length() <= 500) {
					productDescription.setShortDescription( productDescription.getShortDescription() + model.getShortDescriptionSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getShortDescriptionFindAndReplaceOldString())) {
					String newString = productDescription.getShortDescription().replace(model.getShortDescriptionFindAndReplaceOldString(),	model.getShortDescriptionFindAndReplaceNewString());
					if (newString.length() <= 500)
						productDescription.setShortDescription(newString);
				}
				break;
			default: break;	
		}
		
	}
	/**
	 * 设置详细描述
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditFullDescription(Product product,	ProductUniBulkEditModel model) {
		if(model.getFullDescriptionCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		ProductDescription productDescription = product.getProductDescription();
		switch(model.getFullDescriptionMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				productDescription.setFullDescription(model.getFullDescription());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getFullDescriptionPrefix()) && (model.getFullDescriptionPrefix() + productDescription.getFullDescription()).length() <= 20000) {
					productDescription.setFullDescription(model.getFullDescriptionPrefix() + productDescription.getFullDescription());
				}
				if (StringUtils.isNotBlank(model.getFullDescriptionSuffix()) && (model.getFullDescriptionSuffix() + productDescription.getFullDescription()).length() <= 20000) {
					productDescription.setFullDescription( productDescription.getFullDescription() + model.getFullDescriptionSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getFullDescriptionFindAndReplaceOldString())) {
					String newString = productDescription.getFullDescription().replace(model.getFullDescriptionFindAndReplaceOldString(),	model.getFullDescriptionFindAndReplaceNewString());
					if (newString.length() <= 20000)
						productDescription.setFullDescription(newString);
				}
				break;
			default: break;	
		}
		
		
	}
	/**
	 * 修改标题
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditTitle(Product product,ProductUniBulkEditModel model) {
		if(model.getTitleCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getTitleMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				product.setTitle(model.getTitle());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getTitlePrefix()) && (model.getTitlePrefix() + product.getTitle()).length() <= 100) {
					product.setTitle(model.getTitlePrefix() + product.getTitle());
				}
				if (StringUtils.isNotBlank(model.getTitleSuffix()) && (model.getTitleSuffix() + product.getTitle()).length() <= 100) {
					product.setTitle( product.getTitle() + model.getTitleSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getTitleFindAndReplaceOldString())) {
					String newString = product.getTitle().replace(model.getTitleFindAndReplaceOldString(),	model.getTitleFindAndReplaceNewString());
					if (newString.length() <= 100)
						product.setTitle(newString);
				}
				break;
			default: break;	
		}
		
		
	}
	
	/**
	 * 设置meta关键词
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditMetaKeyword(Product product,	ProductUniBulkEditModel model) {
		if(model.getMetaKeywordCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getMetaKeywordMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				product.setMetaKeyword(model.getMetaKeyword());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getMetaKeywordPrefix()) && (model.getMetaKeywordPrefix() + product.getMetaKeyword()).length() <= 250) {
					product.setMetaKeyword(model.getMetaKeywordPrefix() + product.getMetaKeyword());
				}
				if (StringUtils.isNotBlank(model.getMetaKeywordSuffix()) && (model.getMetaKeywordSuffix() + product.getMetaKeyword()).length() <= 250) {
					product.setMetaKeyword( product.getMetaKeyword() + model.getMetaKeywordSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getMetaKeywordFindAndReplaceOldString())) {
					String newString = product.getMetaKeyword().replace(model.getMetaKeywordFindAndReplaceOldString(),	model.getMetaKeywordFindAndReplaceNewString());
					if (newString.length() <= 250)
						product.setMetaKeyword(newString);
				}
				break;
			default: break;	
		}
		
	}
	
	/**
	 * 设置meta描述
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditMetaDescription(Product product,		ProductUniBulkEditModel model) {
		if(model.getMetaDescriptionCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getMetaDescriptionMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				product.setMetaDescription(model.getMetaDescription());
				break;
			case ProductConstants.BULKEDIT_KIND_ADD:
				if (StringUtils.isNotBlank(model.getMetaDescriptionPrefix()) && (model.getMetaDescriptionPrefix() + product.getMetaDescription()).length() <= 250) {
					product.setMetaDescription(model.getMetaDescriptionPrefix() + product.getMetaDescription());
				}
				if (StringUtils.isNotBlank(model.getMetaDescriptionSuffix()) && (model.getMetaDescriptionSuffix() + product.getMetaDescription()).length() <= 250) {
					product.setMetaDescription( product.getMetaDescription() + model.getMetaDescriptionSuffix());
				}
				break;
			case ProductConstants.BULKEDIT_KIND_REPLACE:
				if (StringUtils.isNotBlank(model.getMetaDescriptionFindAndReplaceOldString())) {
					String newString = product.getMetaDescription().replace(model.getMetaDescriptionFindAndReplaceOldString(),	model.getMetaDescriptionFindAndReplaceNewString());
					if (newString.length() <= 250)
						product.setMetaDescription(newString);
				}
				break;
			default: break;	
		}
		
	}
	/**
	 * 修改售价
	 * @param sku
	 * @param model
	 */
	private void doUniBulkEditPrice(ProductSku sku,	ProductUniBulkEditModel model) {
		if(model.getPriceCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getPriceMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				sku.setPrice(new BigDecimal(model.getPrice()));
				break;
			case ProductConstants.BULKEDIT_KIND_FORMULA:
				BigDecimal numeric = new BigDecimal(model.getPriceNumeric());
				switch(model.getPriceMethodOperator()){
					case ProductConstants.PRICE_METHOD_OPERATOR_ADD:
						sku.setPrice(sku.getPrice().add(numeric));
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_SUB:
						if (numeric.compareTo(sku.getPrice()) <= 0) {
							sku.setPrice(sku.getPrice().add(numeric.negate()));
						}
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_PLS:
						sku.setPrice(sku.getPrice().multiply(numeric));
						break;
					default :break;	
				}
				break;
			
			default: break;	
		}
		
	}
	/**
	 * 修改特价
	 * @param sku
	 * @param model
	 */
	private void doUniBulkEditSalePrice(ProductSku sku,	ProductUniBulkEditModel model) {
		if(model.getSalePriceCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getSalePriceMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				if (!StringUtils.isBlank(model.getSalePrice())) {
					sku.setSalePrice(new BigDecimal(model.getSalePrice()));
				} else {
					sku.setSalePrice(null);
				}
				break;
			case ProductConstants.BULKEDIT_KIND_FORMULA:
				BigDecimal numeric = new BigDecimal(model.getSalePriceNumeric());
				if (null == sku.getSalePrice()) {
					// 如果没有特价，必须先给一个默认值
					sku.setSalePrice(new BigDecimal("0"));
				}
				switch(model.getSalePriceMethodOperator()){
					case ProductConstants.PRICE_METHOD_OPERATOR_ADD:
						sku.setSalePrice(sku.getSalePrice().add(numeric));
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_SUB:
						if (numeric.compareTo(sku.getSalePrice()) <= 0) {
							sku.setSalePrice(sku.getSalePrice().add(numeric.negate()));
						}
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_PLS:
						sku.setSalePrice(sku.getSalePrice().multiply(numeric));
						break;
					default :break;	
				}
				break;
			
			default: break;	
		}
		
	}
	/**
	 * 修改市场价
	 * @param sku
	 * @param model
	 */
	private void doUniBulkEditListPrice(ProductSku sku,	ProductUniBulkEditModel model) {
		if(model.getListPriceCheck().shortValue() != Constants.FLAG_TRUE)return;
		
		switch(model.getListPriceMethod()){
			case ProductConstants.BULKEDIT_KIND_MODIFY:
				if (!StringUtils.isBlank(model.getListPrice())) {
					sku.setListPrice(new BigDecimal(model.getListPrice()));
				} else {
					sku.setListPrice(null);
				}
				break;
			case ProductConstants.BULKEDIT_KIND_FORMULA:
				BigDecimal numeric = new BigDecimal(model.getListPriceNumeric());
				if (null == sku.getListPrice()) {
					// 如果没有特价，必须先给一个默认值
					sku.setListPrice(new BigDecimal("0"));
				}
				switch(model.getListPriceMethodOperator()){
					case ProductConstants.PRICE_METHOD_OPERATOR_ADD:
						sku.setListPrice(sku.getListPrice().add(numeric));
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_SUB:
						if (numeric.compareTo(sku.getListPrice()) <= 0) {
							sku.setListPrice(sku.getListPrice().add(numeric.negate()));
						}
						break;
					case ProductConstants.PRICE_METHOD_OPERATOR_PLS:
						sku.setListPrice(sku.getListPrice().multiply(numeric));
						break;
					default :break;	
				}
				break;
			
			default: break;	
		}
		
	}
	/**
	 * 修改批发价
	 * @param sku
	 * @param model
	 */
	private void doUniBulkEditWholePrice(ProductSku sku,	ProductUniBulkEditModel model) {
		if(model.getWpPriceCheck().shortValue() != Constants.FLAG_TRUE || null == model.getWpMinQuantitys())return; 
		wholesalePriceManager.doBulkEditWholesalePriceFromArrays(sku, model.getWpMinQuantitys(), model.getWpMaxQuantitys(), model.getWpPrices());
	}
	/**
	 * 修改重量
	 * @param sku
	 * @param model
	 */
	private void doUniBulkEditWeight(ProductSku sku,	ProductUniBulkEditModel model) {
		if(model.getWeightCheck().shortValue() != Constants.FLAG_TRUE)return;
		if (StringUtils.isNotBlank(model.getWeight())) {
			sku.setWeight(new BigDecimal(model.getWeight()));
		} else {
			sku.setWeight(null);
		}
	}
	/**
	 * 保存商品媒体
	 * @param product
	 * @param model
	 */
	private void doUniBulkEditMedia(Product product,	ProductUniBulkEditModel model) {
		if(ArrayUtils.isEmpty(model.getMediaUrls()))return;
		if( (model.getAccessoryCheck().shortValue() == Constants.FLAG_FALSE )&& (model.getImageCheck().shortValue() == Constants.FLAG_FALSE))return;
		for(int i=0; i< model.getMediaUrls().length; i++){
			
			if(!((model.getImageCheck().shortValue() == Constants.FLAG_TRUE && model.getMediaTypes()[i].equals(ProductMedia.TYPE_IMAGE.toString()))
			|| (model.getAccessoryCheck().shortValue() == Constants.FLAG_TRUE && model.getMediaTypes()[i].equals(ProductMedia.TYPE_ACCESSORY.toString())))){
				//情况：(勾选了图片，但没有上传图片，却添加了附件) 或者 (勾选了附件，但没有上传附件，却添加了图片)
				continue;
			}
			ProductMedia productMedia = new ProductMedia();
			if(model.getImageCheck().shortValue() == Constants.FLAG_TRUE && model.getMediaTypes()[i].equals(ProductMedia.TYPE_IMAGE.toString())){
				productMedia.setMediaType(ProductMedia.TYPE_IMAGE);
				if(StringUtils.isBlank(product.getImageUrl())){
					//如果还没有设置主图，则设置主图
					product.setImageUrl(model.getMediaUrls()[i]);
				}
			}else if(model.getAccessoryCheck().shortValue() == Constants.FLAG_TRUE && model.getMediaTypes()[i].equals(ProductMedia.TYPE_ACCESSORY.toString())){
				
				productMedia.setMediaType(ProductMedia.TYPE_ACCESSORY);
			}
			productMedia.setMediaDescription(model.getMediaDescs()[i]);
			productMedia.setMediaUrl(model.getMediaUrls()[i]);
			productMedia.setProduct(product);
			productMedia.setSortOrder(ProductMedia.DEFAULT_SORTORDER);
			productMediaManager.save(productMedia);
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#doUniBulkEdit(com.probiz.estore.product.model.ProductUniBulkEditModel)
	 */
	public Map<String, Object> doUniBulkEdit(ProductUniBulkEditModel model){
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		for(Integer productId : model.getProductIds()){
			Product product = productManager.getById(productId);
			doUniBulkEditProductName(product,model);
			doUniBulkEditCategory(product,model);
			doUniBulkEditStatus(product,model);
			doUniBulkEditSalesMeasureUnitName(product,model);
			doUniBulkEditMinOrderQuantity(product,model);
			doUniBulkEditBrand(product,model);
			doUniBulkEditKeywords(product,model);
			doUniBulkEditShortDescription(product,model);
			doUniBulkEditFullDescription(product,model);
			doUniBulkEditTitle(product,model);
			doUniBulkEditMetaKeyword(product,model);
			doUniBulkEditMetaDescription(product,model);
			doUniBulkEditMedia(product,model);
			for(ProductSku sku: product.getProductSkus()){
				doUniBulkEditPrice(sku,model);
				doUniBulkEditSalePrice(sku,model);
				doUniBulkEditListPrice(sku,model);
				doUniBulkEditWholePrice(sku,model);
				doUniBulkEditWeight(sku,model);
				
				productSkuManager.save(sku);
			}
			
			//修改价格
			if(null != product.getDefaultProductSku().getSalePrice()){
				product.setPrice(product.getDefaultProductSku().getSalePrice());
			}else{
				product.setPrice(product.getDefaultProductSku().getPrice());
			}
			
			
			productManager.save(product);
			productDescriptionManager.save(product.getProductDescription());
			
		}
		return returnMsgs;
	}
	
	
	public Map<String, Object> doAssBulkEdit(ProductFullyModel model){
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		// start:保存SKU信息
		List<String> newSkuIds = productSkuManager.savePricesFromArrays(returnMsgs, model.getSkuIds(), model.getListPrices(), model.getPrices(), model.getSalePrices(), model.getWeights());
		returnMsgs.put("newSkuIds", newSkuIds);
		for(String productId : model.getProductIds()){
			Product product = productManager.getById(Integer.parseInt(productId));
			ProductSku defaultSku = productSkuManager.getById(product.getDefaultProductSkuId());
			if(null != defaultSku.getSalePrice()){
				product.setPrice(defaultSku.getSalePrice());
			}else{
				product.setPrice(defaultSku.getPrice());
			}
		}
		// end:保存SKU信息
		
		// -----import
		String[] wpSkuIds = getNewWpSkuIds(model.getOldSkuIds(), newSkuIds,
				model.getOldWpSkuIds());

		// start:保存wholesalePrice信息
		List<String> newWpIds = wholesalePriceManager
				.saveWholesalePriceFromArrays(newSkuIds.toArray(new String[0]),wpSkuIds, model.getWpIds(), model
						.getWpMinQuantitys(), model.getWpMaxQuantitys(), model
						.getWpPrices(), model.getWpDeliveryDays());
		returnMsgs.put("newWpIds", newWpIds);
		returnMsgs.put("newWpSkuIds", wpSkuIds);
		// end:保存wholesalePrice信息
		// start:保存库存信息
		inventoryManager.saveInventorysFromArrays(newSkuIds.toArray(new String[0]), model.getInventorys());
		// end:保存库存信息
		
		return returnMsgs;
	}
	
	

	

	// start:与统计相关
	/**
	 * 根据fieldName改变产品统计对应field的值。count为改变数量，可以为正，也可以为负。
	 * 特别注意，这里直接执行sql，不要用load再save的方法。因为前台在并发的时候会遇到乐观锁问题，同时对性能也有所提高。
	 */
	private void updateStatField(Integer productId, String fieldName,
			Integer count) {
		ProductStat productStat = productManager.getById(productId).getProductStat();
		if (null != productStat) {
			productManager.updateStatField(productStat.getProductStatId(), fieldName, count);
		}
	}

	// 增加一个浏览数量
	public void doIncreaseOneViewCount(Integer productId) {
		updateStatField(productId, "viewCount", 1);
	}

	// 增加一个购买次数
	public void doIncreaseOneBuyTimes(Integer productId) {
		updateStatField(productId, "buyTimes", 1);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#doUpdateStatBuyCount(java.lang.Integer, java.lang.Integer)
	 */
	public void doUpdateStatBuyCount(Integer productId,Integer buyCount){
		updateStatField(productId, "buyCount", buyCount.intValue());
	}

	// 增加一个好评
	public void doIncreaseOnePositiveRate(Integer productId) {
		updateStatField(productId, "numOfPositiveRate", 1);
	}

	// 增加一个中评
	public void doIncreaseOneNeutralRate(Integer productId) {
		updateStatField(productId, "numOfNeutralRate", 1);
	}

	// 增加一个差评
	public void doIncreaseOneNegativeRate(Integer productId) {
		updateStatField(productId, "numOfNegativeRate", 1);
	}

	// 减少一个浏览数量
	public void doDecreaseOneViewCount(Integer productId) {
		updateStatField(productId, "viewCount", -1);
	}

	// 减少一个购买次数
	public void doDecreaseOneBuyTimes(Integer productId) {
		updateStatField(productId, "buyTimes", -1);
	}

	// 减少一个好评
	public void doDecreaseOnePositiveRate(Integer productId) {
		updateStatField(productId, "numOfPositiveRate", -1);
	}

	// 减少一个中评
	public void doDecreaseOneNeutralRate(Integer productId) {
		updateStatField(productId, "numOfNeutralRate", -1);
	}

	// 减少一个差评
	public void doDecreaseOneNegativeRate(Integer productId) {
		updateStatField(productId, "numOfNegativeRate", -1);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#checkSkuIsInUse(java.lang.Integer)
	 */
	public boolean checkSkuIsInUse(Integer productSkuId){
		OrderService orderService = (OrderService)ContextUtil.getSpringBeanById("orderService");
		return orderService.getProductSkuCircsInSalesOrder(productSkuId) != 2;
	}
	
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#getProductAttGroupsAndValues(com.probiz.estore.product.model.Product)
	 */
	public List<ProductAttGroup> getProductAttGroupsAndValues(Product product) {
		//获取产品自定义值属性
		Set<ProductAttrValue> productAttrValues = product.getProductAttrValues();
		
		//获取与产品类型关联的自定义属性组
		List<ProductAttGroup> productAttGroups = productAttGroupManager.getProductAttGroupsByProductTypeId(product.getProductTypeId());
		//将产品自定义属性附加在自定义属性组的productAttrValues（辅助前台显示自定义属性）
		for (ProductAttGroup productAttGroup : productAttGroups) {
			Set<ProductAttGroupItem> productAttGroupItems = productAttGroup.getProductAttGroupItems();
			for (ProductAttGroupItem productAttGroupItem : productAttGroupItems) {
				Iterator iterator = productAttrValues.iterator();
				while(iterator.hasNext()){
					ProductAttrValue productAttrValue = (ProductAttrValue)iterator.next();
					if (productAttGroupItem.getId().intValue() == productAttrValue.getProductAttGroupItemId().intValue()) {
						
						List<ProductAttrValue> productAttrValueList = productAttGroup.getProductAttrValues();
						if (productAttrValueList == null) {
							productAttrValueList = new ArrayList<ProductAttrValue>();
							productAttGroup.setProductAttrValues(productAttrValueList);
						}
						productAttrValueList.add(productAttrValue);
						iterator.remove();
					}
				}
				
			}
			if(null == productAttGroup.getProductAttrValues()){
				//如果属性组中没有任何属性，也需设置一个空list
				productAttGroup.setProductAttrValues(new ArrayList<ProductAttrValue>());
			}
		}
		
		return productAttGroups;
		
	}
	
	
	
	/**--------------------------------------------------------------------------
	 *                        <b>快速搜索的URI格式说明<b>
	 *URI格式:http://[path]/[navigationCategory]/cat[categoryId]-{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}...-{n}.html                    
	 * 其中参数的定义为：
	 * 		productFilter在productFilterGroup的索引值。
	 * 		{0} - 价格搜索值在价格搜索组中的位置。例：搜索组为 价格:全部 1000以下 1000 - 2000 2000 - 3000 3000 - 4000 4000 - 5000 5000以上 
	 * 			  那么1000 - 2000对应的URI应为 .....cat[categoryId]-2-{1}-{2}-{3}-...-{n}....
	 * 		{1}  属性搜索值在当前属性搜索组中的位置。例：搜索组为 手机类型:   全部 拍照 音乐 智能 商务 GPS导航 
	 * 			  那么商务对应的URI应为 ....cat[categoryId]-{0}-4-{2}-{3}-...-{n}....
	 *      {2}..{n}  与 {1}的解析同理。
	 *      
	 *      
	 * 例子：
	 * 价格	尺码	颜色	用料
	 * 全部	全部	全部	全部
	 * 100	小码	红色	棉质
	 * 200	中码	绿色	丝质
	 * 300 	大码	蓝色	羊毛
	 * 
	 *  那么它的URI格式应为：http://[path]/[navigationCategory]/cat[categoryId]-{0}-{1}-{2}-{3}.html
	 *  如果选中 价格是200，尺码是全部，用料是蓝色，用料是棉质，那么它对应的具体URI应为：http://[path]/[navigationCategory]/cat[categoryId]-2-0-3-1.html
	 *      
	 *      
	 * 
	 --------------------------------------------------------------------------*/
	
	/**
	 * 创建的标准URI格式MssageFormat 。
	 * 即创建格式http://[path]/[navigationCategory]/cat[categoryId]-{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}...-{n}.html 
	 * @param category 产品目录
	 * @URI uri
	 * @return messageFormat
	 */
	private MessageFormat createURIFormat(ProductCategory productCategory, String URI) {
		String prefix = "";
		if(URI.contains("/cat")){
			prefix = URI.substring(0, URI.lastIndexOf("cat")) + "cat";
		}else if(URI.contains("/searchProd")){
			prefix = URI.substring(0, URI.lastIndexOf("searchProd")) + "searchProd";
		}
		
		StringBuilder format = new StringBuilder();
		format.append(prefix).append(productCategory.getCategoryId()).append("-{0}-{1}");//价格-品牌
		int size = 2; //标识已用过的parameter编号个数
		Long searchAttrCount = productAttGroupItemManager.getNumOfQuickSearchAttItemsByProductTypeId(productCategory.getProductType().getProductTypeId());
		int i=0;
		while(i<searchAttrCount){
			format.append("-{" + (i + size) + "}");
			i++;
		}
		
		size += searchAttrCount.intValue();
		
		Long searchSkuOptionCount = skuOptionManager.getNumOfQuickSearchOptionsByProductTypeId(productCategory.getProductType().getProductTypeId());
		i=0;
		while(i<searchSkuOptionCount){
			format.append("-{" + (i + size) + "}");
			i++;
		}
		
		format.append(".html");
		return new MessageFormat(format.toString());
	}
	
	/**
	 * 初始化产品搜索过滤器的参数
	 * @param 产品目录
	 * @return Integer[] 
	 **/
	private Integer[] initProductFilterParameters(ProductType productType) {	
		List<Integer> parameters = new ArrayList<Integer>();
		
		//价格参数
		parameters.add(Integer.valueOf(0));
		
		//品牌参数
		parameters.add(Integer.valueOf(0));
		
		//快速搜索属性参数
		Long searchAttrCount = productAttGroupItemManager.getNumOfQuickSearchAttItemsByProductTypeId(productType.getProductTypeId());
		int i=0;
		while(i<searchAttrCount){
			parameters.add(Integer.valueOf(0));
			i++;
		}
		//快速搜索规格参数
		Long searchSkuOptionCount = skuOptionManager.getNumOfQuickSearchOptionsByProductTypeId(productType.getProductTypeId());
		i=0;
		while(i<searchSkuOptionCount){
			parameters.add(Integer.valueOf(0));
			i++;
		}
		return parameters.toArray(new Integer[0]);
	}
	
	

	/**
	 * 创建产品过滤器
	 * @param uriFormat		URI格式
	 * @param parameters	URI格式对应的参数。数组中的值代表对应的搜索条件的编号
	 * @param locator		当前搜索条件在参数数组中的位置
	 * @param itemIndex		搜索值的编号，从1开始（0代表忽略该条件）
	 * @param label			标签，用于页面显示
	 * @return
	 */
	private ProductFilter createProductFilter(MessageFormat uriFormat, Integer[] parameters, int locator, int itemIndex, String label,String queryString) {	
		ProductFilter filter = new ProductFilter();
		filter.setSelected((itemIndex == parameters[locator]));
		filter.setLabel(label);
		Integer[] updateParameters = (Integer[])ArrayUtils.clone(parameters);
		updateParameters[locator] = Integer.valueOf(itemIndex); 
		String path = uriFormat.format((ArrayUtil.integerArrayToStringArray(updateParameters)));
		if(StringUtils.isNotBlank(queryString)){
			path += "?"+queryString;
		}
		filter.setPath(path);
		
		return filter;
	}
	
	
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#generateProductFilters(com.probiz.estore.common.model.catalog.ProductCategory, java.lang.String)
	 */
	public List<ProductFilterGroup> generateProductFilters(ProductCategory productCategory, String URI,String queryString){
		List<ProductFilterGroup> result = new ArrayList<ProductFilterGroup>();
		MessageFormat uriFormat = createURIFormat(productCategory, URI);
		Integer[] parameters = null;
		try {
			//从URI中获得快速搜索的参数
			Object[] o = (Object[])uriFormat.parse(URI);
			parameters = new Integer[o.length];
			for (int i = 0; i < o.length; i ++) {
				parameters[i] = Integer.valueOf((String)o[i]); 
			}
		} catch (ParseException e) {
			//解释失败 则初始化一个基本的参数集合。
			parameters = initProductFilterParameters(productCategory.getProductType());
		}
		//产生价格搜索项
		List<PriceInterval> priceIntervals = productTypeManager.getPriceIntervalsByProductType(productCategory.getProductType());
		if (priceIntervals != null && !priceIntervals.isEmpty()) {
			ProductFilterGroup priceProductFilterGroup = new ProductFilterGroup();
			priceProductFilterGroup.setLabel(I18nUtil.getInstance().getMessage("product.price"));
			priceProductFilterGroup.addFilter(createProductFilter(uriFormat, parameters, URI_PRICE_LOCATOR, 0, I18nUtil.getInstance().getMessage("product.search.all"),queryString));
			int itemIndex = 1;
			for (PriceInterval priceInterval : priceIntervals) {
				String label = priceInterval.getLabel();
				if (priceInterval.isRightUnbounded()) {
					label = priceInterval.getMinValue() + I18nUtil.getInstance().getMessage("product.price.above");
				}
				if (priceInterval.isLeftUnbouned()) {
					label = priceInterval.getMaxValue() + I18nUtil.getInstance().getMessage("product.price.below");
				}
				ProductFilter filter = createProductFilter(uriFormat, parameters, URI_PRICE_LOCATOR,itemIndex, label,queryString);
				itemIndex ++;
				priceProductFilterGroup.addFilter(filter);
			}
			result.add(priceProductFilterGroup);
		}
		//产生品牌搜索项
		Set<ProductTypeBrand> productTypeBrands = productCategory.getProductType().getProductTypeBrands();
		if (productTypeBrands != null && productTypeBrands.size() > 0) {
			ProductFilterGroup brandProductFilterGroup = new ProductFilterGroup();
			brandProductFilterGroup.setLabel(I18nUtil.getInstance().getMessage("product.search.brand"));
			brandProductFilterGroup.addFilter(createProductFilter(uriFormat, parameters, URI_BRAND_LOCATOR,0, I18nUtil.getInstance().getMessage("product.search.all"),queryString));
			int itemIndex = 1;
			for (ProductTypeBrand productTypeBrand : productTypeBrands) {
				ProductFilter filter = createProductFilter(uriFormat, parameters,URI_BRAND_LOCATOR, productTypeBrand.getBrand().getBrandId(), productTypeBrand.getBrand().getBrandName(),queryString);
				itemIndex ++;
				brandProductFilterGroup.addFilter(filter);
			}
			result.add(brandProductFilterGroup);
		}
		
		//产生属性搜索项
		List<ProductAttGroupItem> searchAttrList = productAttGroupItemManager.getQuickSearchAttItemsByProductTypeId(productCategory.getProductType().getProductTypeId());
		
		if (!searchAttrList.isEmpty()) {
			int attrIndex = 0;
			for (ProductAttGroupItem searchAttr : searchAttrList) {
				if(searchAttr.getAttribute().getStatus().equals(Constants.FLAG_FALSE))continue;//非激活不用显示
				ProductFilterGroup attrProductFilterGroup = new ProductFilterGroup();
				attrProductFilterGroup.setLabel(searchAttr.getAttribute().getAttributeName());
				attrProductFilterGroup.setShowStyle(searchAttr.getShowStyle());
				String[] searchValues = searchAttr.getSearchValue().replace("，", ",").split(",");
				if (searchValues != null && searchValues.length > 0) {
					attrProductFilterGroup.addFilter(createProductFilter(uriFormat, parameters, URI_ATTR_LOCATOR+attrIndex, 0, I18nUtil.getInstance().getMessage("product.search.all"),queryString));
					for (int j = 0; j < searchValues.length; j ++) {
						int itemIndex = j + 1;
						ProductFilter filter = createProductFilter(uriFormat, parameters, URI_ATTR_LOCATOR+attrIndex, itemIndex, searchValues[j],queryString);
						attrProductFilterGroup.addFilter(filter);
					}
				}
				attrIndex ++;
				result.add(attrProductFilterGroup);
			}
		}
		
		//产生规格值搜索项
		int uriOptionLocator = URI_ATTR_LOCATOR + searchAttrList.size();
		List<SkuOption> searchSkuOptionList = skuOptionManager.getQuickSearchSkuOptionsByProductTypeId(productCategory.getProductType().getProductTypeId());
		if (searchSkuOptionList != null && !searchSkuOptionList.isEmpty()) {
			int skuOptionIndex = 0;
			for(SkuOption skuOption: searchSkuOptionList){
				ProductFilterGroup optionProductFilterGroup = new ProductFilterGroup(ProductFilterGroup.TYPE_SKUOPTIONVALUE);
				optionProductFilterGroup.setLabel(skuOption.getSkuOptionName());
				ProductFilter filter =createProductFilter(uriFormat, parameters, uriOptionLocator+skuOptionIndex, 0, I18nUtil.getInstance().getMessage("product.search.all"),queryString);
				filter.setItemIndex(0);//用于界面呈现
				optionProductFilterGroup.addFilter(filter);
				int itemIndex=1;
				for(SkuOptionValue skuOptionValue : skuOption.getSkuOptionValues()){ 
					filter = createProductFilter(uriFormat, parameters, uriOptionLocator+skuOptionIndex, skuOptionValue.getSkuOptionValueId(), skuOptionValue.getSkuOptionValueName(),queryString);
					filter.setItemIndex(skuOptionValue.getSkuOptionValueId());//用于界面呈现
					optionProductFilterGroup.addFilter(filter);
					itemIndex ++;
				}
				skuOptionIndex ++;
				result.add(optionProductFilterGroup);
			}
			
		}
		
		return result;
	}
	
	
	public ProductSearchCriteria setProductQuickSearchCriteria(ProductSearchCriteria productSearchCriteria,ProductCategory productCategory, String URI) {
		
		MessageFormat uriFormat = createURIFormat(productCategory, URI);
		
		Integer[] parameters = null;
		try {
			Object[] o = (Object[])uriFormat.parse(URI);
			parameters = new Integer[o.length];
			for (int i = 0; i < o.length; i ++) {
				parameters[i] = Integer.valueOf((String)o[i]); 
			}
		} catch (ParseException e) {
			parameters = initProductFilterParameters(productCategory.getProductType());
		}
		
		//设置价格搜索条件
		List<PriceInterval> priceIntervals = productTypeManager.getPriceIntervalsByProductType(productCategory.getProductType());
		int selectedPriceIndex = parameters[URI_PRICE_LOCATOR].intValue();
		if (selectedPriceIndex > 0 && priceIntervals != null && priceIntervals.size() > 0) {
			PriceInterval priceInterval = priceIntervals.get(selectedPriceIndex - 1);
			//provide a margin of error of plus or minus 10%
			BigDecimal lowestPrice = new BigDecimal(priceInterval.getMinValue());// * 0.9
			BigDecimal highestPrice = new BigDecimal(priceInterval.getMaxValue());// * 1.1
			productSearchCriteria.setLowestPrice(lowestPrice);
			productSearchCriteria.setHighestPrice(highestPrice);
		}
		
		//设置品牌搜索条件
		int selectedBrandIndex = parameters[URI_BRAND_LOCATOR].intValue();
		if (selectedBrandIndex > 0 ) {
			productSearchCriteria.setBrandIds(new String[]{String.valueOf(selectedBrandIndex)});
		}
		
		//设置属性搜索条件
		List<ProductAttGroupItem> searchAttrList = productAttGroupItemManager.getQuickSearchAttItemsByProductTypeId(productCategory.getProductType().getProductTypeId());
		if (searchAttrList.size() > 0) {
			List<String> attributeIds = new ArrayList<String>();
			List<String> attributeValues = new ArrayList<String>();
			for (int i = 0; i < searchAttrList.size(); i ++) {
				int selectedAttrIndex = parameters[URI_ATTR_LOCATOR + i].intValue();
				if (selectedAttrIndex > 0) {
					ProductAttGroupItem attItem = searchAttrList.get(i);
					attributeIds.add(attItem.getAttribute().getAttributeId().toString());
					String[] searchValues = attItem.getSearchValue().replace("，", ",").split(",");
					attributeValues.add(searchValues[selectedAttrIndex-1]);
				}
			}
			productSearchCriteria.setAttributeIds(attributeIds.toArray(new String[0]));
			productSearchCriteria.setAttributeValues(attributeValues.toArray(new String[0]));
		}
		//设置规格搜索条件
		int uriOptionLocator = URI_ATTR_LOCATOR+searchAttrList.size();
		List<String> optionValueIds = new ArrayList<String>();
		for(int i=uriOptionLocator; i<parameters.length; i++){
			if(parameters[i]>0){
				optionValueIds.add(String.valueOf(parameters[i]));
			}
		}
		productSearchCriteria.setOptionValueIds(optionValueIds.toArray(new String[0]));
		
		return productSearchCriteria;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#findMapOfRelatedSkuOptionAndValues(com.probiz.estore.common.model.product.Product)
	 */
	
	public Map<SkuOption, Set<SkuOptionValue>> findMapOfRelatedSkuOptionAndValues(Product	product){
		HashMap<SkuOption, Set<SkuOptionValue>> mapOfRelated = new HashMap<SkuOption, Set<SkuOptionValue>>();
		for(ProductSku sku :product.getProductSkus()){
			for(ProductSkuOptionValue relation  : sku.getProductSkuOptionValues()){
				SkuOptionValue skuOptionValue =  relation.getSkuOptionValue();
				SkuOption skuOption = skuOptionValue.getSkuOption();
				
				if(mapOfRelated.containsKey(skuOption)){
					mapOfRelated.get(skuOption).add(skuOptionValue);
				}else{
					Set<SkuOptionValue> setOfValues = new LinkedHashSet<SkuOptionValue>();
					setOfValues.add(skuOptionValue);
					mapOfRelated.put(skuOption, setOfValues);
					
				}
			}
		}
		//start:重排规格顺序
		LinkedHashMap<SkuOption, Set<SkuOptionValue>> mapOfRelatedSorted = new LinkedHashMap<SkuOption, Set<SkuOptionValue>>();
		Set<ProductTypeSkuOption> productTypeSkuOptions = product.getProductType().getProductTypeSkuOptions();
		for(ProductTypeSkuOption productTypeSkuOption : productTypeSkuOptions){
			if(mapOfRelated.containsKey(productTypeSkuOption.getSkuOption())){
				mapOfRelatedSorted.put(productTypeSkuOption.getSkuOption(), mapOfRelated.get(productTypeSkuOption.getSkuOption()));
			}
		}
		//end:重排规格顺序
		return mapOfRelatedSorted;
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#findMapOfRelatedSkuOptionAndValue(com.probiz.estore.common.model.product.ProductSku)
	 */
	public Map<SkuOption ,SkuOptionValue> findMapOfRelatedSkuOptionAndValue (ProductSku  productSku){
		LinkedHashMap<SkuOption, SkuOptionValue> mapOfRelated = new LinkedHashMap<SkuOption, SkuOptionValue>();
		Set<ProductTypeSkuOption> productTypeSkuOptions = productSku.getProduct().getProductType().getProductTypeSkuOptions();
		for(ProductTypeSkuOption productTypeSkuOption : productTypeSkuOptions){
			for(ProductSkuOptionValue relation:productSku.getProductSkuOptionValues()){
				if(relation.getSkuOptionValue().getSkuOption().getSkuOptionId().equals(productTypeSkuOption.getSkuOption().getSkuOptionId())){
					mapOfRelated.put(productTypeSkuOption.getSkuOption(), relation.getSkuOptionValue());
				}
			}
		}
		return mapOfRelated;
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#getProductJSONDataForFront(com.probiz.estore.common.model.product.Product)
	 * 最终结果：
	 * {
	 *    productSkus:【productSkuCode,imageUrl,skuOptionAndValueArray:【skuOptionId,skuOptionName,skuOptionValueId,skuOptionValueName】  】
	 * }
	 */
	public JSONObject getProductJSONDataForFront(Product product){
		JSONObject jsonProduct = new JSONObject();
		JSONArray jsonSkuList = new JSONArray();
		for(ProductSku sku: product.getProductSkus()){
			JSONObject jsonSku = new JSONObject();
			jsonSku.put("productSkuId", sku.getProductSkuId());
			jsonSku.put("productSkuCode", sku.getProductSkuCode());
			jsonSku.put("imageUrl", sku.getImageUrl());
			if(null!=sku.getWeight()){
				BigDecimal weight = sku.getWeight().setScale(2, BigDecimal.ROUND_HALF_UP);
				jsonSku.put("weight", weight.toString());
			}else{
				jsonSku.put("weight", "");
			}
			Map<SkuOption ,SkuOptionValue> mapOfRelatedSkuOptionAndValue = findMapOfRelatedSkuOptionAndValue(sku);
			JSONArray jsonSkuOptionAndValueArray = new JSONArray();
			for(Entry<SkuOption,SkuOptionValue> entry: mapOfRelatedSkuOptionAndValue.entrySet()){
				JSONObject jsonSkuOptionAndValue = new JSONObject();
				jsonSkuOptionAndValue.put("skuOptionId", entry.getKey().getSkuOptionId());
				jsonSkuOptionAndValue.put("skuOptionName", entry.getKey().getSkuOptionName());
				jsonSkuOptionAndValue.put("skuOptionValueId", entry.getValue().getSkuOptionValueId());
				jsonSkuOptionAndValue.put("skuOptionValueName", entry.getValue().getSkuOptionValueName());
				jsonSkuOptionAndValueArray.add(jsonSkuOptionAndValue);
			}
			jsonSku.put("skuOptionAndValueArray", jsonSkuOptionAndValueArray);
			jsonSku.put("availableQuantity", sku.getInventory().getAvailableQuantity());
			jsonSkuList.add(jsonSku);
		}
		jsonProduct.put("minOrderQuantity", (product.getMinOrderQuantity()==null)?1:product.getMinOrderQuantity());
		jsonProduct.put("salesMeasureUnitName", product.getSalesMeasureUnitName());
		jsonProduct.put("productSkus", jsonSkuList);
		return jsonProduct;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProdMainManager#getCompareProductsFromRequest(javax.servlet.http.HttpServletRequest)
	 */
	public List<Product> getCompareProductsFromRequest(HttpServletRequest request){
		String PRODUCTIDS_COOKIENAME = "compareCart_productIds";
		String PRODUCTTYPEID_COOKIENAME ="compareCart_productTypeId";
		String _ITEM_SEPERATOR ="_ITEM_SEPERATOR";
		
		
		Cookie[] cookies = request.getCookies();
		if (!ArrayUtils.isEmpty(cookies)) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(PRODUCTIDS_COOKIENAME)) {
					String productIdStr = cookie.getValue();
					if(StringUtils.isNotBlank(productIdStr)){
						String[] productIdArray = productIdStr.split(_ITEM_SEPERATOR);
						List<Product> productList = new ArrayList<Product>();
						List<String> productIdList = new ArrayList<String>();
						for(int i=0; i<productIdArray.length; i++){
							Product product = productManager.getById(Integer.valueOf(productIdArray[i]));
							if(null!=product && product.getStatus().equals(Product.STATUS_ACTIVE)){
								productList.add(product);
								productIdList.add(product.getProductId().toString());
							}
							
						}
						//start:用于更新服务器cookie
						request.setAttribute(PRODUCTIDS_COOKIENAME, StringUtil.arrayToString(productIdList.toArray(new String[1]), _ITEM_SEPERATOR));
						request.setAttribute(PRODUCTTYPEID_COOKIENAME, (productList.size()!=0)?productList.get(0).getProductTypeId():"");
						//end:  用于更新服务器cookie
						return productList;
					}
				}
			}
		}
		return new ArrayList<Product>();
	}
	

}
